package com.ruoyi.framework.config;

import com.ruoyi.common.core.domain.model.AppLoginUser;
import com.ruoyi.common.core.domain.model.AppLoginUserV3;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * app 用户拦截器
 *
 * @author liuliya
 */
@Component
public class AppInterceptorV3Config implements HandlerInterceptor {

    private static final String APP_HEADER_KEY = "flag";
    private static final String APP_HEADER_VALUE = "app";

    private static final List<String> ignoreUrls = Arrays.asList("/wyhc/login","/wyhc/v3/login");

    @Autowired
    private TokenService tokenService;

    /**
     * 返回false 会终端操作
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appHeaderValue = request.getHeader(APP_HEADER_KEY);
        if (StringUtils.isBlank(appHeaderValue)) {
            throw new ServiceException("请求头需要传flag标识", 403);
        }
        if (!APP_HEADER_VALUE.equals(appHeaderValue)) {
            throw new ServiceException("请求头需要传flag标识的值为app", 403);
        }
        if (ignoreUrls.contains(request.getRequestURI())) {
            return true;
        }
        AppLoginUserV3 appLoginUser = tokenService.getAppLoginUserV3(request);
        if (null == appLoginUser) {
            throw new ServiceException("登录状态已过期，请重新登录", 401);
        }
        return true;
    }
}
